import axios from 'axios'
import http from '@/utils/http'

const BASE_URL = '/wecom/meeting'
axios.defaults.baseURL = 'https://meeting.fortunesemic.com/api'
/** @desc 会议列表 */
export function getMeetingList(query) {
  return http.get(`${BASE_URL}`, query)
}

/**
 * 获取会议室占用状态
 * @param officeBuildingId 办公楼 ID
 */
export const getRoomStatus = async (officeBuildingId: number) => {
  try {
    const response = await axios.get(`/wecom/usestatus/${officeBuildingId}`)
    if (response.data.code === '0' && response.data.success) {
      return response.data.data // 返回会议室状态数据
    } else {
      throw new Error(response.data.msg || '获取会议室状态失败')
    }
  } catch (error) {
    console.error('请求会议室状态失败:', error)
    throw error
  }
}
/**
 * 获取厂区列表
 */
export const getFactoryList = () => {
  return axios.get('/wecom/factory').then((res) => {
    if (res.data.code === '0' && res.data.success) {
      return res.data.data // 返回厂区数组
    } else {
      throw new Error(res.data.msg || '获取厂区失败')
    }
  })
}

/**
 * 获取办公楼列表
 * @param factoryId 厂区 ID
 */
export const getBuildingList = (factoryId: number) => {
  return axios.get(`/wecom/building?id=${factoryId}`).then((res) => {
    if (res.data.code === '0' && res.data.success) {
      return res.data.data // 返回办公楼数组
    } else {
      throw new Error(res.data.msg || '获取办公楼失败')
    }
  })
}

interface AvailableRoomsParams {
  buildingId: number
  floor: string
  factoryId: number
  startTime: string
  continuedTime: number
}

/**
 * 获取可用会议室列表
 */
export const getAvailableRooms = async (params: AvailableRoomsParams) => {
  try {
    const response = await axios.post('/wecom/availablerooms', params)
    if (response.data.code === '0' && response.data.success) {
      return response.data.data
    } else {
      throw new Error(response.data.msg || '获取会议室失败')
    }
  } catch (error) {
    console.error('请求会议室失败:', error)
    throw error
  }
}

export const scheduleMeeting = async (meetingData: any) => {
  try {
    const response = await axios.post('/wecom/orderMeet', meetingData)
    console.error('预约会议 API 返回:', response.data)
    if (response.data.success === true || response.data.code === '0' || String(response.data.code) === '0') {
      return response.data.data
    } else {
      throw new Error(response.data.msg || '预约会议失败')
    }
  } catch (error) {
    console.error('请求预约会议失败:', error)
    throw error
  }
}
export const getUserTree = async () => {
  try {
    const response = await axios.get('/wecom/apptree')
    console.error('用户树 API 返回数据:', response.data)
    if (response.data.code === '0' && response.data.success) {
      return response.data.data
    } else {
      throw new Error(response.data.msg || '获取用户树失败')
    }
  } catch (error) {
    console.error('请求用户树失败:', error)
    throw error
  }
}
/**
 * 取消会议
 * @param conferenceId 会议ID
 * @returns 取消会议的响应
 */
export const escMeeting = async (conferenceId: number | string) => {
  try {
    const response = await axios.get(`/wecom/cancelmeet?conference_id=${conferenceId}`)
    if (response.data.code === '0' && response.data.success) {
      return response
    } else {
      throw new Error(response.data.msg || '取消会议失败')
    }
  } catch (error) {
    console.error('请求取消会议失败:', error)
    throw error
  }
}

/** @desc 历史会议列表 */
export function getHistoryMeetingList(userId: string | number | null) {
  return http.get(`/wecom/getWecomMeetHistory?userId=${userId}`)
}
/** @desc 根据办公楼id获取楼层列表 */
export function getAvailableFloor(buildingId: number) {
  return http.get(`/wecom/availableFloor?buildingId=${buildingId}`)
}

/** @desc 根据楼层查询可用会议室 */
export function getAvailablerooms(body: any) {
  return http.post(`/system/meet/availablerooms`, body)
}

// 在src/apis/startApp/meeting.ts中添加搜索接口
export const searchUsersAndDevices = async (keyword: string) => {
  try {
    const response = await axios.get('/wecom/search', {
      params: { keywords: keyword }
    })
    console.error('搜索接口返回:', response.data)
    if (response.data.code === '0' && response.data.success) {
      return response.data.data
    }
    throw new Error(response.data.msg || '搜索失败')
  } catch (error) {
    console.error('搜索请求失败:', error)
    throw error
  }
}

/** @desc 模糊搜索组织架构 */
export function wecomApptreeSearch() {
  return http.get(`/wecom/apptree/search`)
}

/** @desc 上传会议室图片 */
export function uploadAvatar() {
  return http.post(`/user/file`)
}

/** @desc 根据周期会议对象查询会议 */
export function getEndDatw(data: any) {
  return http.post(`/oa/checkCycle`, data)
}

/**
 * 搜索组织架构树
 * @param keyword 搜索关键字
 */
export const searchTree = (keyword: string) => {
  return http.get(`/contects/apptree/search?keyword=${encodeURIComponent(keyword)}`)
}

/**
 * 获取会议详情
 * @param conferenceId 会议ID
 * @param userId 用户ID
 * @returns 会议详情的响应
 */
export const getMeetInfo = async (conferenceId: string, userId?: string) => {
  const response = await axios.get(`/wecom/meetInfo`, {
    params: {
      conferenceId,
      userId
    }
  })
  return response.data
}

/**
 * 取消已预约的会议
 * @param params 包含conferenceId的参数对象
 * @returns 取消会议的响应
 */
export const cancelSchedule = async (params: { conferenceId: string }) => {
  try {
    const response = await axios.post('/wecom/cancelSchedule', params)
    if (response.data.code === 0 && response.data.success) {
      return response.data
    } else {
      throw new Error(response.data.msg || '取消会议失败')
    }
  } catch (error) {
    console.error('请求取消会议失败:', error)
    throw error
  }
}

/**
 * 编辑会议
 * @param meetingData 会议数据，需包含conferenceId
 */
export const updateMeeting = async (meetingData: any) => {
  try {
    const response = await axios.post('/wecom/updateMeet', meetingData)
    // 直接返回 response.data，包含 code/msg/success/data
    return response.data
  } catch (error) {
    console.error('请求编辑会议失败:', error)
    throw error
  }
}

/**
 * 查询单独会议室
 */
export const getRoom = async (id: number) => {
  try {
    const response = await axios.get(`/wecom/getRoom`, { params: { id } })
    if (response.data.code === '0' && response.data.success) {
      return response.data.data
    } else {
      throw new Error(response.data.msg || '获取会议室失败')
    }
  } catch (error) {
    console.error('请求会议室失败:', error)
    throw error
  }
}

/**
 * 会议冲突检测
 * @param data MeetConflictDTO
 * @returns 冲突检测结果
 */
export const meetConflict = async (data: any) => {
  try {
    const response = await axios.post('/wecom/meetConflict', data)
    return response.data
  } catch (error) {
    console.error('会议冲突检测失败:', error)
    throw error
  }
}
